<template>
  <div class="mainControl">
    <VonCrumbs title="配方管理"></VonCrumbs>
    <div class="widget">
      <VonInput v-model="searchCondition" width="260px" placeholder="搜索配方" @change="getRecipes">
      </VonInput>
      <el-button type="primary" size="small" @click="add" class="addButton">
        添加
      </el-button>
    </div>
    <div class="tableContent">
      <VonTable :column="column" :tableData="tableData">
        <template slot="num">
          <el-table-column label="序号" align="center" width="100px">
            <template slot-scope="scope">
              {{scope.$index+1}}
            </template>
          </el-table-column>
        </template>
        <template slot="operation">
          <el-table-column align="center" label="操作" width="200">
            <template slot-scope="scope">
              <el-button type="text" size="small" style="color: #1890ff" @click="edit(scope.row,'view')">
                查看
              </el-button>
              <el-button type="text" size="small" style="color: #1890ff" @click="edit(scope.row,'edit')">
                编辑
              </el-button>
              <!-- <el-button type="text" size="small" style="color: #1890ff" @click="del(scope.row)">
                删除
              </el-button> -->
            </template>
          </el-table-column>
        </template>
      </VonTable>
    </div>
    <VonDialog :title="type==1?'新增':TYPE == 'view'?'查看':'编辑'" @cancelResult="cancelResult" @commitResult='commitResult' :isShow_Popup="isShow_Popup">
      <div class="deviceForm" slot="content">
        <el-form ref="form" :model="form" label-width="48px">
          <el-form-item>
            <VonInput v-model="form.name" label="配方名称" width="460px" :disabled="TYPE == 'view'"></VonInput>
          </el-form-item>
          <el-form-item>
            <div v-if="TYPE == 'view'" class="viewRecipeInfo">
              <p class="viewRecipeInfoTitle">物料信息:</p>
              <p class="viewRecipeInfoContent">
                <span v-for="item in materialOptions">{{item.name}}</span>
              </p>
            </div>
            <VonSelect v-model="form.materialId"
                       v-else
                       :options="materialOptions"
                       :isMultiple="true"
                       label="物料信息"
                       width="460px"
                       >
            </VonSelect>
          </el-form-item>
          <el-form-item>
            <el-row class="RecipeManageForm">
              <div v-for="(item,index) in details" :key="index">
                <el-col :span="7" :offset="1">
                  <p>工站</p>
                  <p class="workStation">{{item.workStationName}}</p>
                </el-col>
                <el-col :span="8">
                  <p>设备</p>
                  <VonSelect width="90px" :options="deviceOptions" style=" margin: 10px 0;" height="30px" v-model="item.deviceId" @change="changed(item)" :disabled="TYPE == 'view'">
                  </VonSelect>
                </el-col>
                <el-col :span="8">
                  <p>超时时间</p>
                  <VonInput width="90px" style=" margin: 10px 0;" height="30px" v-model="item.timeout" :suffix="false" :disabled="TYPE == 'view'">
                  </VonInput>
                </el-col>
              </div>
            </el-row>
          </el-form-item>
        </el-form>
      </div>
    </VonDialog>
  </div>
</template>
<script>
import {
  getRecipeListApi,
  createRecipe,
  deleteRecipe,
  getMaterialOptions,
  getWorkStationOptions,
  getDeviceOptions,
  recipeUpdate
} from "../../api/workStation/mainControl";
import { openLoading, closeLoading } from "../../common/prompt";
import { setTimeout } from "timers";
export default {
  name: "RecipeManage",
  data() {
    return {
      searchCondition: "",
      tableData: [],
      type: 0,
      form: {},
      isShow_Popup: false,
      details: [],
      materialOptions: [],
      deviceOptions: [],
      deviceAllOptions: [],
      workStationOptions: [],
      TYPE:'edit',
      column: [
        {
          align: "center",
          label: "配方",
          prop: "name"
        },
        {
          align: "center",
          label: "物料信息",
          prop: "materials"
        },
        {
          align: "center",
          label: "工站-设备",
          prop: "details"
        }
      ]
    };
  },
  created() {
    this.getRecipes();
    this.getOptions();
  },
  methods: {
    getOptions() {
      getMaterialOptions().then(res => {
        this.materialOptions = res.data;
      });
      getWorkStationOptions().then(res => {
        this.workStationOptions = res.data;
        this.details = [];
        res.data.forEach(d =>
          this.details.push({
            workStationId: d.id,
            workStationName: d.name,
            timeout: "",
            isSelect: false
          })
        );
      });
      getDeviceOptions().then(res => {
        this.deviceOptions = this.deviceAllOptions = res.data;
      });
    },
    getRecipes() {
      openLoading();
      let query = {};
      if (this.searchCondition) {
        query = { name: this.searchCondition };
      }
      getRecipeListApi(query).then(res => {
        closeLoading();
        if (res.data && res.status == 200) {
          this.tableData = res.data;
          this.tableData.forEach(t => {
            let materials = [],
              details = [];
            t.recipeMaterials.forEach(m => {
              materials.push(m.materialName);
            });
            t.recipeDetails.forEach(m => {
              details.push(m.workStationName + "-" + m.deviceName);
            });
            t.materials = materials.join();
            t.details = details.join();
          });
        } else {
          this.$message.error("查询数据失败");
        }
      });
    },
    commitResult() {
      let details = this.details.filter(d => d.isSelect);
      if (!this.form.name) {
        this.$message.error("请填写名称");
        return;
      }
      if (!this.form.materialId) {
        this.$message.error("请选择物料");
        return;
      }
      if (details.length == 0) {
        this.$message.error("请选择工站设备");
        return;
      }
      for (let i = 0; i < details.length; i++) {
        const item = details[i];
        if (!item.timeout) {
          item.timeout = 0;
        }
      }
      this.form.recipeDetails = details;
      this.form.recipeMaterials = [];
      this.form.materialId.forEach(m =>
        this.form.recipeMaterials.push({ materialId: m })
      );
      openLoading("处理中...");
      if (this.type == 1) {
        createRecipe(this.form).then(res => {
          this.isShow_Popup = false;
          if (res.status == 200 || res.status == 204) {
            this.$message.success("新增成功");
            this.getRecipes();
          } else {
            this.$message.error("添加失败");
          }
        });
      } else {
        recipeUpdate(this.form).then(res => {
          this.isShow_Popup = false;
          if (res.status == 200 || res.status == 204) {
            this.$message.success("修改成功");
            this.getRecipes();
          } else {
            this.$message.error("添加失败");
          }
        });
      }
    },
    cancelResult() {
      //重置
      this.details.forEach(d => {
        d.deviceId = "";
        d.timeout = "";
        d.isSelect = false;
      });
      this.deviceOptions = this.deviceAllOptions;
      this.isShow_Popup = false;
    },
    add() {
      //重置
      this.details.forEach(d => {
        d.deviceId = "";
        d.timeout = "";
        d.isSelect = false;
      });
      this.deviceOptions = this.deviceAllOptions;
      this.form = {};
      this.type = 1;
      this.isShow_Popup = true;
    },
    edit(row,TYPE) {
      this.type = 2;
      this.TYPE = TYPE;
      this.isShow_Popup = true;
      setTimeout(() => {
        let { id, name, recipeDetails, recipeMaterials } = row;
        this.form = {
          id,
          name,
          recipeDetails,
          recipeMaterials,
          materialId: []
        };
        this.form.recipeMaterials.forEach(d =>
          this.form.materialId.push(d.materialId)
        );
        this.details.forEach(d => {
          this.form.recipeDetails.forEach(rd => {
            if (rd.workStationId == d.workStationId) {
              d.deviceId = rd.deviceId;
              d.timeout = rd.timeout;
              d.isSelect = true;
            }
          });
        });
        const selectItems = [];
        this.details.forEach(d => {
          if (d.isSelect) {
            selectItems.push(d.deviceId);
          }
        });
        this.deviceOptions = this.deviceAllOptions.filter(
          d => !selectItems.includes(d.id)
        );
      }, 0);
    },
    del(row) {
      this.$confirm("是否确认操作？").then(() => {
        let data = { id: row.id };
        deleteRecipe(data).then(res => {
          this.isShow_Popup = false;
          if (res.status == 200 || res.status == 204) {
            this.$message.success("删除成功");
            this.getRecipes();
          } else {
            this.$message.error("删除失败");
          }
        });
      });
    },
    changed(item) {
      if (item.deviceId) {
        item.isSelect = true;
      } else {
        item.isSelect = false;
      }
      const selectItems = [];
      this.details.forEach(d => {
        if (d.isSelect) {
          selectItems.push(d.deviceId);
        }
      });
      this.deviceOptions = this.deviceAllOptions.filter(
        d => !selectItems.includes(d.id)
      );
    }
  }
};
</script>
<style scoped lang="scss">
@import "../../style/mainControl";
.deviceForm {
  height: 700px;
  overflow-y: scroll;
  .viewRecipeInfo{
    margin-left: 11px;
    .viewRecipeInfoTitle{
      height: 30px;
      line-height: 30px;
      color: white;
      font-size: 16px;
    }
    .viewRecipeInfoContent{
      margin-left: 11px;
      line-height: 30px;
      span{
        margin-right: 10px;
      }
    }
  }
}
</style>

